package src.hash;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class no18 {

    //四数之和，双指针
    public static void main(String[] args) {
        int[] arr = {1, 0, -1, 0, -2, 2};
        int target = 0;
        List<List<Integer>> res = fourSum(arr, target);
        for (List<Integer> list : res) {
            System.out.println(list);
        }

    }

    public static List<List<Integer>> fourSum(int[] nums, int target) {
        List<List<Integer>> res = new ArrayList<>();
        Arrays.sort(nums);

        //i内层for，j外层for，left左指针，right右指针
        for (int j = 0; j < nums.length; j++) {
            //一级剪枝
            if (nums[j] > target && nums[j] >= 0) {
                break;
            }
            //一级去重
            if (j > 0 && nums[j] == nums[j - 1]) {
                continue;
            }


            for (int i = j + 1; i < nums.length; i++) {
                int left = i + 1;
                int right = nums.length - 1;
                //二级剪枝
                if (nums[i] + nums[j] > target && nums[i] + nums[j]>= 0) {
                    break;
                }
                //二级去重
                if (i > j + 1 && nums[i] == nums[i - 1]) {
                    continue;
                }

                while (left < right) {
                    int sum = nums[i] + nums[j] + nums[left] + nums[right];

                    if (sum > target) {
                        right--;
                    } else if (sum < target) {
                        left++;
                    } else {
                        res.add(Arrays.asList(nums[j], nums[i], nums[left], nums[right]));
                        while (left < right && nums[left] == nums[left + 1]) {
                            left++;
                        }
                        while (left < right && nums[right] == nums[right - 1]) {
                            right--;
                        }
                        left++;
                        right--;
                    }

                }
            }
        }
        return res;

    }
}
